package cn.dt.ymcc.userdetails;

import cn.dt.ymcc.domain.Login;
import cn.dt.ymcc.domain.Permission;
import cn.dt.ymcc.mapper.PermissionMapper;
import cn.dt.ymcc.service.ILoginService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class LoginUserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private ILoginService loginService;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Wrapper<Login> wrapper = new EntityWrapper<>();
        wrapper.eq("username",username);
        Login login = loginService.selectOne(wrapper);

        //查询权限
        List<Permission> permissions = permissionMapper.loadPermissionsByLoginId(login.getId());
        //登录用户对应的权限
        List<SimpleGrantedAuthority> authorities = permissions.stream().map(permission ->
            new SimpleGrantedAuthority(permission.getSn())).collect(Collectors.toList());
        return new User(
                login.getUsername(),
                login.getPassword(),
                login.getEnabled(),
                login.getAccountNonExpired(),
                login.getCredentialsNonExpired(),
                login.getAccountNonLocked(),
                authorities
                );
    }
}